package com.example.demo.limit.redis;

import com.example.demo.limit.LimitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author lyc
 * @date 2019/6/11.
 */
@Service
@Slf4j
public class ResdisLimitServiceImpl implements LimitService {

    @Autowired
    private RedisTemplate redisTemplate;
    ExecutorService exec = Executors.newCachedThreadPool();// 线程池
    @Override
    public void limit() {
        //这里我用 包名+类名+方法
        String key = "com.example.demo.limit.redis.ResdisLimitServiceImpl.limit";

        RedisAtomicLong counter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
        for (int i = 0; i < 100; i++) {
            final int no = i;
            exec.submit(new Runnable() {
                @Override
                public void run() {
                    if (counter.incrementAndGet() > 10) {
                        //拒绝请求
                        log.info("拒绝请求{}", no);
                    }
                    try {
                        //处理请求
                        log.info("处理请求{}", no);
                    } finally {
                        counter.decrementAndGet();
                    }
                    try {
                        Thread.sleep((long) (Math.random() * 10000));
                    } catch (InterruptedException e) {

                    }
                }
            });
        }
    }


}